package  {
	
	import ca.dominion.heritageQuiz.globals.*;
	import ca.dominion.heritageQuiz.projectComponents.Background;
	import ca.dominion.heritageQuiz.quiz.*;
	import ca.dominion.heritageQuiz.quiz.data.*;
	import ca.dominion.heritageQuiz.utils.*;
	
	import caurina.transitions.properties.TextShortcuts;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.Security;

	[SWF (width=600, height=400, frameRate=31, backgroundColor=0xFFFFFF)]
	
	public class MainSite extends Sprite {
		
		private var _xmlLoader:XMLLoader;
		private var _background:Background;
		private var _quiz:Quiz;
		private var _imageCacher:ImageCacher;
		
		public function MainSite() {
			
			//Security.allowDomain("www.macdonald-laurier.ca");
			TextShortcuts.init();
			stage.stageFocusRect = false;
			_xmlLoader = new XMLLoader();
			_background = new Background();
			_xmlLoader.load(Config.CONFIG_URL, setConfigData);
			_imageCacher = new ImageCacher();
			
		}
		
		private function setConfigData(e:Event):void {
			
			Config.PROJECT_XML = XML(e.target.data);
			Config.COPY = root.loaderInfo.parameters.lang == "fr" ? Config.PROJECT_XML.francais[0] : Config.PROJECT_XML.english[0];
			//Config.COPY = root.loaderInfo.parameters.lang == "fr" ? Config.PROJECT_XML.english[0] : Config.PROJECT_XML.francais[0]; 
			
			_quiz = new Quiz();
			_quiz.addEventListener(InteractiveEvent.RESET_QUIZ, loadQuiz);
			
			addChild(_background);
			loadQuiz();
			
		}
		
		
		
		private function loadQuiz(e:Event = null):void {
			
			var url:String = Config.COPY.quizData.@url + Math.ceil( Math.random() * 5 ).toString() + ".xml";
			_xmlLoader.load( url, createQuiz);
			
		}
		
		
		
		private function createQuiz(e:Event):void {
			
			var questions:QuestionArray = new QuestionArray();
			var images:Array = new Array();
			
			var imageFolder:String = Config.PROJECT_XML.imageFolder.@src;
			
			for each(var item:XML in XMLList(XML(e.target.data).question)) {
				var question:Question = new Question();
				question.id = item.@id;
				question.text = item.text.toString();
				question.options = XMLList(item.option);
				question.imageURL = imageFolder + item.@url.toString();
				question.answer = item.answer.toString();
				question.response = item.explanation.toString();
				
				images.push(question.imageURL);
				questions.push(question); 
			}
			
			_imageCacher.loadImageList(images);
			_quiz.init(questions);
			addChild(_quiz);
			
		}
		
	}
}
